import 'dotenv/config';
import {createServer}from 'http';
const PORT=process.env.PORT;

const users=[
    {id:1,name:'张三'},
    {id:2,name:'李四'},
    {id:3,name:'王五'}
];
//Logger中间件
const logger=(req,res,next)=>{
    console.log(`${req.method} ${req.url}`);
    next();
};

//JSON中间件
const jsonMiddleware=(req,res,next)=>{
    res.setHeader('Content-Type','application/json;charset=utf-8');
    next();
}

//路由器处理GET /api/users
const getUsersHandler=(req,res)=>{
    res.write(JSON.stringify(users));
    res.end();
};

const getUserHandler=(req,res)=>{
    const id=req.url.split('/')[3];
    const user=users.find(user=>user.id==id);
        
        if(user){
            res.write(JSON.stringify(user));
        }else{
            res.statusCode=404;
            res.write(JSON.stringify({message:'用户不存在'}));
        }
        res.end();
    };
const notFoundHandler=(req,res)=>{
    res.statusCode=404;
    res.write(JSON.stringify({message:'API不存在'}));
    res.end();    
};

//路由处理POST /api/users
const createUserHandler=(req,res)=>{
    let body='';
    req.on('data',(chunk)=>{
        body+=chunk.toString();
    });
    req.on('end',()=>{
        const user=JSON.parse(body);
        users.push(user);
        res.reponseCode=201;
        res.write(JSON.stringify(user));
        res.end();
    });
};

const server=createServer((req,res)=>{
    logger(req,res,()=>{
        jsonMiddleware(req,res,()=>{
        if(req.url==='/api/users'&&req.method==='GET'){
            getUsersHandler(req,res);
        }else if(req.url.startsWith('/api/users/')&&req.method==='GET'){
            getUserHandler(req,res);
        }else if(req.url==='/api/users'&&req.method==='POST'){
            createUserHandler(req,res);
        }else{
            notFoundHandler(req,res);
        }
    })
})
    
});

server.listen(PORT,()=>{
    console.log(`服务器已启动，监听端口${PORT}`);
});